package net.homelinux.chaoswg.io.renga.krypto.animations.Add;

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

import net.homelinux.chaoswg.io.renga.core.registries.GlobalPropertyRegistry;
import net.homelinux.chaoswg.io.renga.krypto.datatypes.numerical.UnsignedNBit;

public class AddStateChanger implements Runnable {
    JLabel firstOperandsDisplay;
    JLabel secondOperandsDisplay;
    JLabel resultDisplay;
    JFrame jw;
    
    final AddState initialState;
    
    public AddStateChanger (AddState initialState)  {
        this.initialState = initialState;

        jw = new JFrame ("Add");
        jw.getContentPane().add(getPanel());
        jw.setLocationRelativeTo(null);
        
        jw.setSize(500, 100);
        
        
    }
    
    private JPanel getPanel() {
        JPanel toReturn = new JPanel (new GridLayout (3,1));
        toReturn.add (firstOperandsDisplay = new JLabel (initialState.getAugend().toString()));
        toReturn.add (secondOperandsDisplay = new JLabel (initialState.getAddend().toString()));
        toReturn.add (resultDisplay = new JLabel (initialState.getResult().toString()));

        firstOperandsDisplay.setHorizontalAlignment(JLabel.RIGHT);
        secondOperandsDisplay.setHorizontalAlignment(JLabel.RIGHT);
        resultDisplay.setHorizontalAlignment(JLabel.RIGHT);

        toReturn.setBorder(new BevelBorder (BevelBorder.RAISED));

        return toReturn;
    }

    private void setNew () {
        firstOperandsDisplay.setText (initialState.getAugend().toString());
        firstOperandsDisplay.paintImmediately(firstOperandsDisplay.getVisibleRect());
        secondOperandsDisplay.setText (initialState.getAddend().toString());
        secondOperandsDisplay.paintImmediately(firstOperandsDisplay.getVisibleRect());
        resultDisplay.setText (initialState.getResult().toString());
        resultDisplay.paintImmediately(firstOperandsDisplay.getVisibleRect());
    }

    public void run() {
        int delay = ((Integer)GlobalPropertyRegistry.getGlobalPropertyRegistry().getProperty("animationSpeed")) * 100;

        jw.setVisible(true);

        setNew ();
        UnsignedNBit augend = initialState.getAugend();
        UnsignedNBit addend = initialState.getAddend();
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {System.err.println ("ERR");}

        initialState.setResult(augend.add(addend));
        setNew ();

        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {}
    }

    public void close () {
    	jw.dispose ();
    }
    
}
